//
//  SelectDeviceViewController.m
//  Rail
//
//  Created by hychen on 2018/3/6.
//  Copyright © 2018年 Hychen. All rights reserved.
//

#import "SelectDeviceViewController.h"
#import "LinePointDetailView.h"
#import "SelectDeviceSuperTableViewCell.h"
#import "SelectFactoryFoldCellModel.h"
#import "SelectFactorySectionTableViewCell.h"
#import "SelectFactoryLineTableViewCell.h"
#import "SelectFactoryTableViewCell.h"
#import "ObserverDeviceListViewController.h"


@interface SelectDeviceViewController ()
@property (nonatomic, strong) FactoryTreeModel *treeModel;
@end

/*
 
 2.3.5 + 2.4.1 数据请求
 当点击工区的时候 请求2.4.1并进行展示
 
 */
@implementation SelectDeviceViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self.navigationItem addSimpleTitleView:@"选择设备"];
    
    [self.tableView.mj_header beginRefreshing];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)refreshData {
    BMWeakSelf
    [HttpRequest loadWorkareaListDataSuccess:^(FactoryTreeModel *object) {
        weakSelf.treeModel = object;
        [weakSelf setupTableData];
        [weakSelf.tableView.mj_header endRefreshing];
        [weakSelf.tableView reloadData];
    } failure:^(NSString *code, NSString *msg) {
        Show_Msg_Error(msg)
        [weakSelf.tableView.mj_header endRefreshing];
    }];
}

- (void)setupTableData {
//    NSArray *lineArray = self.treeModel.list;
//    if (lineArray.count > 0) {
//
//        for (int i = 0; i < lineArray.count; ++i) {
//            //线路
//            FactoryTreeLineModel *lineModel = [lineArray objectAtIndex:i];
//            SelectFactoryFoldCellModel *foldCellModel = [SelectFactoryFoldCellModel new];
//            foldCellModel.level = @"0";
//            foldCellModel.obj = lineModel;
//            foldCellModel.belowCount = 0;
//            foldCellModel.submodels =
//            //
//        }
//    }
    
    
}

- (void)setupTableViewData {
    /*
     线路 --
     FactoryTreeLineModel(用于显示线路图)
     FactoryTreeAreaModel
     FactoryTreeAreaModel
     ...
     */
    NSMutableArray *dataArray = [NSMutableArray array];
    for (int i = 0; i < self.treeModel.list.count; ++i) {
        //Section折叠模型
        SelectFactoryFoldCellModel *secFoldModel = [SelectFactoryFoldCellModel new];
        secFoldModel.level = @"0";
        FactoryTreeLineModel *line = [self.treeModel.list objectAtIndexSafe:i];
        line.isSection = YES;
        secFoldModel.obj = line;
        secFoldModel.belowCount = 0;
        NSMutableArray *subArray = [NSMutableArray array];
        //线路Cell折叠模型
        SelectFactoryFoldCellModel *linePathFoldModel = [SelectFactoryFoldCellModel new];
        linePathFoldModel.level = @"0";
        line.isSection = NO;
        linePathFoldModel.obj = line;
        linePathFoldModel.supermodel = secFoldModel;
        [subArray addObject:linePathFoldModel];
        //默认工区折叠模型
        FactoryTreeStationModel *station = line.station_list.firstObject;
        if ([station isKindOfClass:[FactoryTreeStationModel class]] && station.area_list.count > 0) {
            for (int j = 0; j < station.area_list.count; ++j) {
                FactoryTreeAreaModel *model = [station.area_list objectAtIndexSafe:j];
                SelectFactoryFoldCellModel *areaFoldModel = [SelectFactoryFoldCellModel new];
                areaFoldModel.level = @"1";
                areaFoldModel.obj = model;
                areaFoldModel.supermodel = secFoldModel;
                [subArray addObject:areaFoldModel];
            }
            secFoldModel.submodels = subArray;
        }
        [dataArray addObject:secFoldModel];
    }
    
    self.dataArray = dataArray;
    
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    SelectFactoryFoldCellModel *model = [self.dataArray objectAtIndex:indexPath.row];
    if ([model.obj isKindOfClass:[FactoryTreeLineModel class]]) {
        FactoryTreeLineModel *lineModel = (FactoryTreeLineModel *)model.obj;
        if (lineModel.isSection) {
            //sectionCell
            SelectFactorySectionTableViewCell *cell = [SelectFactorySectionTableViewCell cellWithInitStyleTableView:tableView class:[SelectFactorySectionTableViewCell class]];
            cell.model = model;
            return cell;
        }
        else {
            //linePathCell
            SelectFactoryLineTableViewCell *cell = [SelectFactoryLineTableViewCell cellWithInitStyleTableView:tableView class:[SelectFactoryLineTableViewCell class]];
            
            //点击站点/标段回调 -> 刷新数据源
            BMWeakSelf
            [cell setBlockClickButton:^(id obj, SelectFactoryFoldCellModel *cellFoldModel) {
                [weakSelf handleRefreshStationOrSectionWorkAreaDataWithLineModel:cellFoldModel clickObj:obj];
            }];
            
            cell.cellFoldModel = model;
            return cell;
        }
    }
    else if ([model.obj isKindOfClass:[FactoryTreeAreaModel class]]) {
        SelectFactoryTableViewCell *cell = [SelectFactoryTableViewCell cellWithTableView:tableView class:[SelectFactoryTableViewCell class]];
        cell.titleLabel.text = ((FactoryTreeAreaModel *)model.obj).area_name?:@"";
        return cell;
    }
    return [UITableViewCell new];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    SelectFactoryFoldCellModel *model = [self.dataArray objectAtIndex:indexPath.row];
    if ([model.obj isKindOfClass:[FactoryTreeLineModel class]]) {
        FactoryTreeLineModel *lineModel = (FactoryTreeLineModel *)model.obj;
        if (lineModel.isSection) {
            //sectionCell
            return 55.f;
        }
        else {
            //linePathCell
            FactoryTreeLineModel *lineModel = (FactoryTreeLineModel *)model.obj;
            NSInteger count = 0;
            for (FactoryTreeStationModel *stationModel in lineModel.station_list) {
                count++;
                count += stationModel.section_list.count;
            }
            return [SelectFactoryLineTableViewCell heightForSelectFactoryLineCell:count];;
        }
    }
    else if ([model.obj isKindOfClass:[FactoryTreeAreaModel class]]) {
        return 44.f;
    }
    return 0;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    SelectFactoryFoldCellModel *didSelectModel = [self.dataArray objectAtIndex:indexPath.row];
    
    if ([didSelectModel.obj isKindOfClass:[FactoryTreeAreaModel class]]) {
        FactoryTreeAreaModel *areamodel = (FactoryTreeAreaModel *)didSelectModel.obj;
        //工区
        //查看设备列表
        [self gotoSelectObserverVideoDeviceVc:areamodel];
    }
    else if ([didSelectModel.obj isKindOfClass:[FactoryTreeLineModel class]]) {
        FactoryTreeLineModel *lineModel = (FactoryTreeLineModel *)didSelectModel.obj;
        if (lineModel.isSection) {
            //sectionCell
            [tableView beginUpdates];
            if (didSelectModel.belowCount == 0) {
                //展开
                NSArray *submodels = [didSelectModel open];
                NSIndexSet *indexes = [NSIndexSet indexSetWithIndexesInRange:((NSRange){indexPath.row + 1,submodels.count})];
                [self.dataArray insertObjects:submodels atIndexes:indexes];
                
                //Rows
                NSMutableArray *indexPaths = [NSMutableArray new];
                for (int i = 0; i < submodels.count; i++) {
                    NSIndexPath *insertIndexPath = [NSIndexPath indexPathForRow:(indexPath.row + 1 + i) inSection:indexPath.section];
                    [indexPaths addObject:insertIndexPath];
                }
                [tableView insertRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationFade];
            }
            else {
                //收缩
                NSArray *submodels = [self.dataArray subarrayWithRange:((NSRange){indexPath.row + 1,didSelectModel.belowCount})];
                [didSelectModel closeWithSubmodels:submodels];
                [self.dataArray removeObjectsInArray:submodels];
                
                //Rows
                NSMutableArray *indexPaths = [NSMutableArray new];
                for (int i = 0; i < submodels.count; i++) {
                    NSIndexPath *insertIndexPath = [NSIndexPath indexPathForRow:(indexPath.row + 1 + i) inSection:indexPath.section];
                    [indexPaths addObject:insertIndexPath];
                }
                [tableView deleteRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationFade];
            }
            [tableView endUpdates];
        }
        else {
            //linePathCell
            return;
        }
    }
}

- (NSInteger)tableView:(UITableView *)tableView indentationLevelForRowAtIndexPath:(NSIndexPath *)indexPath {
    SelectFactoryFoldCellModel *model = [self.dataArray objectAtIndex:indexPath.row];
    return [model.level integerValue];
}

- (void)handleRefreshStationOrSectionWorkAreaDataWithLineModel:(SelectFactoryFoldCellModel *)cellFoldModel clickObj:(id)obj {
    //父类折叠模型
    SelectFactoryFoldCellModel *superFoldModel = cellFoldModel.supermodel;
    if (superFoldModel.submodels.count > 1) {
        //        [self.tableView beginUpdates];
        //移除旧工区折叠模型
        [superFoldModel.submodels removeObjectsAtIndexes:[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(1, superFoldModel.submodels.count-1)]];
        
        //获取工区模型
        NSArray *areaArray = nil;
        if ([obj isKindOfClass:[FactoryTreeStationModel class]]) {
            areaArray = ((FactoryTreeStationModel *)obj).area_list;
        }
        else if ([obj isKindOfClass:[FactoryTreeSectionModel class]]) {
            areaArray = ((FactoryTreeSectionModel *)obj).area_list;
        }
        //生成新的工区折叠模型数组
        NSMutableArray *subArray = [NSMutableArray array];
        for (int j = 0; j < areaArray.count; ++j) {
            FactoryTreeAreaModel *model = [areaArray objectAtIndexSafe:j];
            SelectFactoryFoldCellModel *areaFoldModel = [SelectFactoryFoldCellModel new];
            areaFoldModel.level = @"1";
            areaFoldModel.obj = model;
            areaFoldModel.supermodel = superFoldModel;
            [subArray addObject:areaFoldModel];
        }
        //添加新的工区折叠模型数组
        [superFoldModel.submodels addObjectsFromArray:subArray];
        
        //        [self.tableView endUpdates];
        
        [self.tableView reloadData];
    }
}

- (void)gotoSelectObserverVideoDeviceVc:(FactoryTreeAreaModel *)areamodel {
    ObserverDeviceListViewController *vc = [ObserverDeviceListViewController new];
    vc.areaId = areamodel.areaid;
    //传空获取全部状态的设备
    vc.status = @"";
    BMWeakSelf
    [vc setBlockCallBack:^(SelectVideoDeviceModel *deviceModel) {
        if (weakSelf.BlockCallBack) {
            weakSelf.BlockCallBack(deviceModel);
        }
    }];
    [self.navigationController pushViewController:vc animated:YES];
}
@end

